<?php
/**
 * Created by PhpStorm.
 * User: HeiYanHeiMao
 * Date: 2020/2/23
 * Time: 11:22
 */

namespace app\controller;

use app\BaseController;
use app\middleware\Check;
use app\model\StoreModel;
use app\Request;
use think\facade\Db;
use think\facade\Validate;
use think\validate\ValidateRule;

require_once '../sdk/WxpayAPI/lib/WxSend.Api.php';
require_once '../sdk/API-PHP/API_PHP_DEMO.php';

/** 商户管理
 * Class Store
 * @package app\controller
 */
class Store extends BaseController
{
    protected $middleware = [Check::class];

    /**经营范围列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function scope_list(Request $request)
    {
        if (!$request->isPost()) return jsonFail('非法请求方式');
        $data = Db::table('eb_scope')->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /**商户信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function store_info(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $store = Store_find($token);
        unset($store['pwd']);
        return jsonSuccess('获取成功', $store);
    }

    /**商户注册
     * @param Request $request
     * @return \think\response\Json
     */
    public function register(Request $request)
    {
        if (!$request->isPost()) return jsonFail('非法请求方式');
        // 接收参数
//        $input['account'] = $request->post('account'); // 商户账号
        $input['pwd'] = $request->post('pwd'); // 商户密码
        $input['repwd'] = $request->post('repwd'); // 商户再次密码
        $input['company_name'] = $request->post('company_name'); // 单位名称
        $input['legal_name'] = $request->post('legal_name'); // 法人名字
        $input['address'] = $request->post('address'); // 地址
        $input['scope_ids'] = $request->post('scope_ids'); // 经营范围ids
        $input['cert_validity'] = $request->post('cert_validity'); // 经营有效期
        $input['cert_pic'] = $request->post('cert_pic'); // 营业执照照片
        $input['allow_pic'] = $request->post('allow_pic'); // 经营许可证件照
        $input['logo'] = $request->post('logo'); // 商铺logo
        $input['shop_name'] = $request->post('shop_name'); // 商铺名称
        $input['send_start'] = $request->post('send_start'); // 配送起始时间
        $input['send_end'] = $request->post('send_end'); // 配送结束时间
        $input['school_ids'] = $request->post('school_ids'); // 可配送学校
        $input['bank_no'] = $request->post('bank_no'); // 银行卡号
        $input['bank_address'] = $request->post('bank_address'); // 开户行
        $input['bank_phone'] = $request->post('bank_phone'); // 银行预留电话
        $input['bank_name'] = $request->post('bank_name'); // 银行预留姓名
//        $input['sn'] = $request->post('sn'); // 打印机编号
        //验证参数
        $validate = Validate::rule([
//            'account' => ValidateRule::isRequire(null, '缺少参数'),
            'pwd' => ValidateRule::isRequire(null, '缺少参数'),
            'repwd' => function ($value, $all) {
                return $value == $all['pwd'] ? true : '两次密码输入不一致';
            },
            'company_name' => ValidateRule::isRequire(null, '缺少参数'),
            'legal_name' => ValidateRule::isRequire(null, '缺少参数'),
            'address' => ValidateRule::isRequire(null, '缺少参数'),
            'scope_ids' => ValidateRule::isRequire(null, '缺少参数'),
            'cert_validity' => ValidateRule::isRequire(null, '缺少参数'),
            'cert_pic' => ValidateRule::isRequire(null, '缺少参数'),
            'allow_pic' => ValidateRule::isRequire(null, '缺少参数'),
            'logo' => ValidateRule::isRequire(null, '缺少参数'),
            'shop_name' => ValidateRule::isRequire(null, '缺少参数'),
            'send_start' => ValidateRule::isRequire(null, '缺少参数'),
            'send_end' => ValidateRule::isRequire(null, '缺少参数'),
            'school_ids' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_no' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_address' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_phone' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_name' => ValidateRule::isRequire(null, '缺少参数'),
//            'sn' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return StoreModel::register($input);
    }

    /**商户登录
     * @param Request $request
     * @return \think\response\Json
     */
    public function login(Request $request)
    {
        if (!$request->isPost()) return jsonFail('非法请求方式');
        // 接收参数
        $input['phone'] = $request->post('phone'); // 商户账号
        $input['pwd'] = $request->post('pwd'); // 商户密码
        //验证参数
        $validate = Validate::rule([
            'phone' => ValidateRule::isRequire(null, '缺少参数'),
            'pwd' => ValidateRule::isRequire(null, '缺少参数')
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return StoreModel::login($input);
    }

    /**商户接单
     * @param Request $request
     * @return \think\response\Json
     */
    public function receiveOrder(Request $request)
    {
        if (!$request->isPost()) return jsonFail('非法请求方式');
        // 接收参数
        $input['id'] = $request->post('id'); // 订单id
        //验证参数
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数')
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return StoreModel::receiveOrder($input, $request->param('token'));
    }

    /**获取商户下商品和分类
     * @param Request $request
     * @return \think\response\Json
     */
    public function goods_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $store = Store_find($token);
        $goods_list = Db::table('eb_category')->select()->toArray();
        $Ids = array_column($goods_list, 'id');
        $goods = Db::table('eb_goods')->where('store_id', $store['id'])->where('cate_id', 'in', $Ids)->select()->toArray();
        foreach ($goods as $otherInfo) {
            $key = array_search($otherInfo['cate_id'], $Ids);
            $goods_list[$key]['goods'][] = $otherInfo;
        }
        return jsonSuccess('获取成功', $goods_list);
    }
    /**修改商品信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function edit_goods(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $goods_id = $this->request->param('goods_id');//商品ID
        $store = Store_find($token);
        $name = $this->request->param('name');//name
        $pic = $this->request->param('pic');//pic
        $price = $this->request->param('price');//price
        $detail = $this->request->param('detail');//detail
        try {
            $res = Db::table('eb_goods')->where('id', $goods_id)->where('store_id', $store['id'])->update([
                'name' => $name,
                'pic' => $pic,
                'price' => $price,
                'detail' => $detail,
            ]);
            if ($res != 0) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }

    /**修改商户信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function edit_store(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $store = Store_find($token);
//        $input['account'] = $request->post('account'); // 单位名称
        $input['company_name'] = $request->post('company_name'); // 单位名称
        $input['legal_name'] = $request->post('legal_name'); // 法人名字
        $input['address'] = $request->post('address'); // 地址
        $input['scope_ids'] = $request->post('scope_ids'); // 经营范围ids
        $input['cert_validity'] = $request->post('cert_validity'); // 经营有效期
        $input['cert_pic'] = $request->post('cert_pic'); // 营业执照照片
        $input['allow_pic'] = $request->post('allow_pic'); // 经营许可证件照
        $input['logo'] = $request->post('logo'); // 商铺logo
        $input['send_start'] = $request->post('send_start'); // 配送起始时间
        $input['send_end'] = $request->post('send_end'); // 配送结束时间
        $input['bank_no'] = $request->post('bank_no'); // 银行卡号
        $input['bank_address'] = $request->post('bank_address'); // 开户行
        $input['bank_phone'] = $request->post('bank_phone'); // 银行预留电话
        $input['bank_name'] = $request->post('bank_name'); // 银行预留姓名
        //验证参数
        $validate = Validate::rule([
//            'account' => ValidateRule::isRequire(null, '缺少参数'),
            'company_name' => ValidateRule::isRequire(null, '缺少参数'),
            'legal_name' => ValidateRule::isRequire(null, '缺少参数'),
            'address' => ValidateRule::isRequire(null, '缺少参数'),
            'scope_ids' => ValidateRule::isRequire(null, '缺少参数'),
            'cert_validity' => ValidateRule::isRequire(null, '缺少参数'),
            'cert_pic' => ValidateRule::isRequire(null, '缺少参数'),
            'allow_pic' => ValidateRule::isRequire(null, '缺少参数'),
            'logo' => ValidateRule::isRequire(null, '缺少参数'),
            'send_start' => ValidateRule::isRequire(null, '缺少参数'),
            'send_end' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_no' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_address' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_phone' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_name' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return StoreModel::edit($input, $store['id']);
    }

    /**修改营业状态
     * @param Request $request
     * @return \think\response\Json
     */
    public function business_status(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $status = $this->request->param('status');//status
        $store = Store_find($token);
        if (is_null($status)) return jsonFail('缺少参数');
        if ($status != 0 && $status != 1) return jsonFail('参数错误');
        try {
            $res = Db::table('eb_store')->where('id', $store['id'])->update(['is_open' => $status]);
            if ($res != 0) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }

    /**修改商铺基本信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function edit_basic(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $shop_name = $this->request->param('shop_name');//shop_name
        $logo = $this->request->param('logo');//logo
        $send_start = $this->request->param('send_start');//send_start
        $send_end = $this->request->param('send_end');//send_end
        $describe = $this->request->param('describe');//describe
        $store = Store_find($token);
        if (empty($shop_name) || empty($logo) || empty($describe) || empty($send_end) || empty($send_start)) return jsonFail('缺少参数');
        try {
            $res = Db::table('eb_store')->where('id', $store['id'])->update([
                'shop_name' => $shop_name,
                'logo' => $logo,
                'describe' => $describe,
                'send_start' => $send_start,
                'send_end' => $send_end,
            ]);
            if ($res != 0) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail('服务器内部错误~');
        }
    }

    /**商家拒绝退款
     * @param Request $request
     * @return \think\response\Json
     */
    public function Refuse_money(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $order_no = $this->request->param('order_no');//订单号
        $unback_reason = $this->request->param('unback_reason');//拒绝退款原因
        if (empty($unback_reason) || empty($order_no)) return jsonFail('缺少参数');
        $order = Db::table('eb_order')->where('order_no', $order_no)->find();
        try {
            $res = Db::table('eb_order')->where('order_no', $order_no)->update(['unback_reason' => $unback_reason, 'status' => 2,'is_refues'=>1]);
            $send = new \WxSendApi();
            $ds = json_decode($send->send_Template_Refuse($order['user_id'], $order), true); //转为数组;
            if ($res != 0 && $ds['errcode'] == 0) return jsonSuccess('操作成功');
            return jsonFail('操作失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }

    /** 商户添加打印机
     * @param Request $request
     */
    public function add_printer(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $store = Store_find($token);
        $sn = $this->request->param('sn');//sn
        $key = $this->request->param('key');//key
        if(empty($sn)||empty($key)) return jsonFail('缺少参数');
        try {
            $res = Db::table('eb_store')->where('id', $store['id'])->update(['sn' => $sn, 'key' => $key]);
            $send = new \API_PHP_DEMO();
            $printerContent = $sn.'#'.$key.'#'.$store['shop_name'].'#';
            $code = $send->printerAddlist($printerContent);
            $data = json_decode($code,true);
            if($res!=0 && $data['ret']==0) return jsonSuccess('添加打印机成功！',$data);
            return jsonFail('添加失败',$data);
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }
    /** 商户测试打印机
     * @param Request $request
     */
    public function test_print(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $store = Store_find($token);
        $send = new \API_PHP_DEMO();
        $arr[0] = array('title'=>'酸菜鱼','price'=>'100.4','num'=>'10');
        $arr[1] = array('title'=>'可乐鸡翅+蒜蓉蒸扇贝','price'=>'10.3','num'=>'6');
        $arr[2] = array('title'=>'紫苏焖鹅+梅菜肉饼+椒盐虾+北京烤鸭','price'=>'10.0','num'=>'8');
        $data = test_prints($arr,14,6,3,6);
        $code = $send->printMsg($store['sn'],$data,1);
        $data = json_decode($code,true);
        if($data['ret']==0) return jsonSuccess('测试成功');
        return jsonFail('测试失败，请联系管理员',$data);
    }
    /** 每日流水
     * @param Request $request
     */
    public function report(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $store = Store_find($token);
        $start_time = $this->request->param('start_time');//开始时间
        $end_time = $this->request->param('end_time');//结束时间
        $status = $this->request->param('status');//订单状态
        if(empty($start_time)||empty($end_time)||is_null($status)) return jsonFail('缺少参数');
        $data['list'] = Db::table('eb_order')->where('store_id',$store['id'])->where('status',$status)->whereTime('create_time', 'between', [$start_time, $end_time])->select()->toArray();
        $data['History_money'] = Db::table('eb_order')->where('store_id',$store['id'])->where('status','>=',5)->sum('delivery_price');
        $data['History_num'] = Db::table('eb_order')->where('store_id',$store['id'])->where('status','>=',5)->count();
        return jsonSuccess('获取成功',$data);
    }
    /**获取所有分类
     * @param Request $request
     * @return \think\response\Json
     */
    public function category_list(Request $request)
    {
        $cate_list = Db::table('eb_category')->select()->toArray();
        return jsonSuccess('获取成功',$cate_list);
    }
    /**获取该分类下商品
     * @param Request $request
     * @return \think\response\Json
     */
    public function cateid_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $cate_id = $this->request->param('cate_id');//分类ID
        $page = $this->request->param('page',1);
        $limit = $this->request->param('limit',10);
        $school_id = $this->request->param('school_id');
        if(empty($cate_id)||empty($school_id)) return jsonFail('缺少参数');
        $eb_school_store = Db::table('eb_school_store')->where('school_id', $school_id)->select()->toArray();
        $storeIDs = array_column($eb_school_store, 'store_id');//商家ID集合
        $store = Db::table('eb_store')->where('id', 'in', $storeIDs)->where('status', 1)->where('is_open',0)->field('id,shop_name,logo,score,is_open')->select()->toArray();
        foreach ($store as $key=>$value) {
            $store[$key]['goods'] = Db::table('eb_goods')->where('cate_id', $cate_id)->where('store_id',$value['id'])->page($page, $limit)->select()->toArray();
            if(empty($store[$key]['goods'])){
                unset($store[$key]['goods']);
                unset($store[$key]);
            }
        }
        return jsonSuccess('获取成功', $store);
    }
    /**修改商品是否售罄
     * @param Request $request
     * @return \think\response\Json
     */
    public function goods_out(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $goods_id = $this->request->param('goods_id');//商品ID
        $is_out= $this->request->param('is_out');//0:正常 1：售罄
        if(is_null($is_out))return jsonFail('缺少参数');
        $store = Store_find($token);
        try {
            $res = Db::table('eb_goods')->where('id', $goods_id)->where('store_id', $store['id'])->update([
                'is_out' => $is_out,
            ]);
            if ($res != 0) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }
    /**修改是否可以退款
     * @param Request $request
     * @return \think\response\Json
     */
    public function is_refuse(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
//        $goods_id = $this->request->param('goods_id');//商品ID
        $is_refues= $this->request->param('is_refues');//0:可退款 1：不可退
        if(is_null($is_refues))return jsonFail('缺少参数');
        $store = Store_find($token);
        try {
            $res = Db::table('eb_store')->where('id', $store['id'])->update([
                'is_refues' => $is_refues,
            ]);
            if ($res != 0) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }
}